using System;
using System.Configuration;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace DataMongo
{
    public class RepositoryBaseMongo: IBaseRepository
    {
        private readonly string collectionName = "";
        private readonly string databaseName = ConfigurationManager.AppSettings["Database"];

        private readonly MongoServer server =
            MongoServer.Create(ConfigurationManager.ConnectionStrings["mongodb"].ToString());

        public RepositoryBaseMongo(string collectionName)
        {
            this.collectionName = collectionName;
        }

        protected MongoCollection<T> GetMongoCollection<T>()
        {
            if (String.IsNullOrEmpty(collectionName))
                throw new InvalidOperationException("CollectionName is either null or empty");
            var database = server.GetDatabase(databaseName);
            var mongoCollection = database.GetCollection<T>(collectionName);
            return mongoCollection;
        }

        #region IBaseRepository Members


        public IQueryable<T> GetAll<T>() {
            return GetMongoCollection<T>().FindAll().AsQueryable();
        }

        public T Find<T>(object id)
        {
            return GetMongoCollection<T>().FindOneById(BsonValue.Create(id));
        }

        public void InsertOrUpdate<T>(T entity) {
            GetMongoCollection<T>().Save(entity);
        }

        public void Delete<T>(object id) {
            GetMongoCollection<T>().FindAndRemove(Query.EQ("_id", BsonValue.Create(id)), null);
        }

        #endregion
    }
}